import React, { useMemo } from 'react';
import GITHUB_LANGUAGES_COLOR from 'configs/githublangs.json';

import Text, { TEXT_VIEW } from 'components/Text';
import { classnames } from 'utils';

import classes from './Languages.module.scss';

export type LanguagesProps = {
    languages: Record<string, number>;
};

const cnLanguages = classnames(classes, 'languages');

const Languages: React.FC<LanguagesProps> = React.memo(({ languages }) => {
    const totalLanguageCount = useMemo(() => Object.values(languages).reduce((sum, cur) => sum + cur, 0), [languages]);

    return (
        <div className={cnLanguages()}>
            <Text view={TEXT_VIEW.p18} className={cnLanguages('text')}>
                Languages
            </Text>
            <div className={cnLanguages('bar')}>
                {Object.entries(languages)
                    .slice(0, 6)
                    .map(([language, languageCount]) => (
                        <div
                            key={`${language}_${languageCount}_color`}
                            style={{
                                width: `${(languageCount / totalLanguageCount) * 100}%`,
                                backgroundColor:
                                    (GITHUB_LANGUAGES_COLOR as Record<string, string>)[language] ?? '#05005d',
                            }}
                        />
                    ))}
            </div>
            <div className={cnLanguages('percentage')}>
                {Object.entries(languages)
                    .slice(0, 6)
                    .map(([language, languageCount]) => (
                        <div key={`${language}_${languageCount}_percentage`} className={cnLanguages('color')}>
                            <div
                                style={{
                                    width: 8,
                                    height: 8,
                                    borderRadius: '50%',
                                    backgroundColor:
                                        (GITHUB_LANGUAGES_COLOR as Record<string, string>)[language] ?? '#05005d',
                                }}
                            />
                            <div className={cnLanguages('language')}>
                                <Text view={TEXT_VIEW.p14}>{language}</Text>
                                <Text view={TEXT_VIEW.p14} color="secondary">
                                    {`${((languageCount / totalLanguageCount) * 100).toFixed(1)}%`}
                                </Text>
                            </div>
                        </div>
                    ))}
            </div>
        </div>
    );
});

export default Languages;
